<template>
  <d2-container>
      <div>
        <d2-crud
            ref="user"
            :columns="users"
            :data="userData"
            add-title="新增员工"
            :form-options="formOptions"
            :add-template="addTemplate"
            @row-add="handleRowAdd"
            @dialog-cancel="handleDialogCancel"
            @row-remove="handleRowRemove"
            :add-rules="addRules"
            :rowHandle="rowHandle"
            :options="options">
          <el-button slot="header" style="margin-bottom: 5px" @click="addUser">新增</el-button>
        </d2-crud>
      </div>
  </d2-container>
</template>

<script>
import { request } from '@/api/service'
import globalAPI from '@/api/globalAPI'

export default {
  data () {
    return {
      users: [
        {
          title: '日期',
          key: 'createTime',
          width: '180'
        },
        {
          title: '姓名',
          key: 'username',
          width: '180'
        },
        {
          title: '备注',
          key: 'desc'
        }
      ],
      userData: [],
      options: {
        height: '250',
        stripe: true
      },
      formOptions: {
        labelWidth: '80px',
        labelPosition: 'left',
        saveLoading: false
      },
      addTemplate: {
        username: {
          title: '姓名',
          value: ''
        },
        password: {
          title: '密码',
          value: '',
          component: {
            name: 'el-input',
            type: 'password'
          }
        }
      },
      addRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 200, message: '长度在 2 到 200个字符', trigger: 'blur' },
          { type: 'string', required: true, pattern: /^[0-9a-zA-Z_]{2,200}$/, message: '由数字字母下划线组成', trigger: 'blur' },
          {
            validator (rule, value, callback) {
              request({
                url: `${globalAPI.BASE_URL}/user/duplicate/v1?username=${value}`,
                method: 'get'
              }).then(ret => {
                if (!ret.data) {
                  callback()
                } else {
                  callback(new Error(`用户名： ${value} 已经存在`))
                }
              })
            },
            trigger: 'blur'
          }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 200, message: '长度在 6 到 200个字符', trigger: 'blur' },
          { type: 'string', required: true, pattern: /^[0-9a-zA-Z_]{6,200}$/, message: '由数字字母下划线组成', trigger: 'blur' }]
      },
      rowHandle: {
        remove: {
          icon: 'el-icon-delete',
          size: 'small',
          fixed: 'right',
          confirm: true,
          show (index, row) {
            return row.showRemoveButton
          },
          disabled (index, row) {
            return row.forbidRemove
          }
        }
      }
    }
  },
  methods: {
    addUser () {
      this.$refs.user.showDialog({
        mode: 'add'
      })
    },
    handleRowAdd (row, done) {
      this.formOptions.saveLoading = true
      request({
        url: `${globalAPI.BASE_URL}/user/v1`,
        method: 'put',
        data: row
      }).then(ret => {
        if (ret.statusCode === 2000) {
          this.$message({
            message: ret.msg,
            type: 'success'
          })
          this.findAllUsers()
          this.formOptions.saveLoading = false
          done()
        } else {
          this.$message({
            message: ret.msg,
            type: 'fail'
          })
          this.formOptions.saveLoading = false
        }
      })
    },
    handleDialogCancel (done) {
      this.$message({
        message: '取消保存',
        type: 'warning'
      })
      done()
    },
    timestampToTime (timestamp) {
      var date = new Date(timestamp * 1000)
      var y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? ('0' + MM) : MM
      let d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      let h = date.getHours()
      h = h < 10 ? ('0' + h) : h
      let m = date.getMinutes()
      m = m < 10 ? ('0' + m) : m
      let s = date.getSeconds()
      s = s < 10 ? ('0' + s) : s
      return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
    },
    findAllUsers () {
      request({
        url: `${globalAPI.BASE_URL}/user/v1`,
        method: 'get'
      }).then(res => {
        if (res.statusCode === 2000) {
          this.userData = res.data
          this.userData.forEach(user => {
            user.createTime = this.timestampToTime(user.createTime)
            user.forbidRemove = false
            user.showRemoveButton = true
          })
        }
      })
    },
    handleRowRemove ({ index, row }, done) {
      console.log(row)
      request({
        url: `${globalAPI.BASE_URL}/user/${row.id}/v1`,
        method: 'delete'
      }).then(res => {
        if (res.statusCode === 2000) {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.findAllUsers()
          this.formOptions.saveLoading = false
          done()
        } else {
          this.$message({
            message: res.msg,
            type: 'fail'
          })
        }
      })
    }
  },
  created () {
    this.findAllUsers()
  }
}
</script>
